package cn.wowjoy.office.materialmanage.inventory;

import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.alibaba.android.arouter.launcher.ARouter;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.List;

import javax.inject.Inject;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.InventoryAdapter;
import cn.wowjoy.office.common.adapter.MenuAdapter;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.ResultEmpty;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.request.AddInventoryRequest;
import cn.wowjoy.office.data.response.InventoryResponse;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Sherily on 2017/12/27.
 * Description:
 */

public class MaterialInventoryViewModel extends NewBaseViewModel {

    @Inject
    ApiService apiService;

    private int startIndex = 0;
    private int pageSize = 10;
    private String status;
    private String keyWord;
    private String storageCode;

    public InventoryAdapter adapter = new InventoryAdapter();
    public LRecyclerViewAdapter lAdapter = new LRecyclerViewAdapter(adapter);
    public MenuAdapter statusMenu = new MenuAdapter();
    public MediatorLiveData<LiveDataWrapper<List<InventoryResponse>>> liveData = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<List<PopuModel>>> menus = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<ResultEmpty>> lockStock = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<ResultEmpty>> addReport = new MediatorLiveData<>();
    public MediatorLiveData<LiveDataWrapper<String>> isChecked = new MediatorLiveData<>();
    MediatorLiveData<LiveDataWrapper<List<PopuModel>>> stockMenu = new MediatorLiveData<>();
    MediatorLiveData<PopuModel>  meun = new MediatorLiveData<>();
    @Inject
    public MaterialInventoryViewModel(@NonNull NewMainApplication application) {
        super(application);
        adapter.setmEventHandle(this);
        statusMenu.setmEventListener(this);
    }


    @Override
    public void loadData(boolean ref) {
        super.loadData(ref);
        getInventory(ref);
    }

    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
        adapter.setKeyword(keyWord);
    }
    public void setData(boolean isRefresh, List<InventoryResponse> inventoryResponses) {
        if (isRefresh) {
            adapter.refresh(inventoryResponses);
        } else {
            adapter.loadMore(inventoryResponses);
        }
        lAdapter.removeFooterView();
        if (!isRefresh && (null == inventoryResponses || inventoryResponses.isEmpty() )){
            LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
            View view = inflater.inflate(R.layout.nodata_footview,null,false);
            lAdapter.addFooterView(view);

        }
        lAdapter.notifyDataSetChanged();
        refreshComplete();
    }

    public void getInventory(boolean isRefresh){
        if (isRefresh){
            startIndex = 0;
        } else {
            ++startIndex;
        }
        liveData.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getCountReportList(status,keyWord,startIndex,pageSize)//, MenuHelper.getAuidS().get("zc_pm")
                .flatMap(new ResultDataParse<List<InventoryResponse>>())
                .compose(new RxSchedulerTransformer<List<InventoryResponse>>())
                .subscribe(new Consumer<List<InventoryResponse>>() {
                               @Override
                               public void accept(List<InventoryResponse> inventoryResponses) throws Exception {
                                   liveData.setValue(LiveDataWrapper.success(inventoryResponses));
                                   setData(isRefresh,inventoryResponses);
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                liveData.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });

        addDisposable(disposable);


    }

    public void getStatus(){
        menus.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.reportStatus()
                .flatMap(new ResultDataParse<List<PopuModel>>())
                .compose(new RxSchedulerTransformer<List<PopuModel>>())
                .subscribe(new Consumer<List<PopuModel>>() {
                               @Override
                               public void accept(List<PopuModel> popuModels) throws Exception {
                                   popuModels.add(0,new PopuModel("全部",true,""));
                                   menus.setValue(LiveDataWrapper.success(popuModels));
                                   statusMenu.setPopuModels(popuModels);
                                   getInventory(true);
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                menus.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });

//        List<PopuModel> list = mockMenu();
        addDisposable(disposable);

    }
    @Override
    public void onCreateViewModel() {

    }
    public void getStock(){
        stockMenu.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getStock()
                .flatMap(new ResultDataParse<List<PopuModel>>())
                .compose(new RxSchedulerTransformer<List<PopuModel>>())
                .subscribe(new Consumer<List<PopuModel>>() {
                               @Override
                               public void accept(List<PopuModel> popuModels) throws Exception {
                                   stockMenu.setValue(LiveDataWrapper.success(popuModels));
                                   if (null != popuModels && !popuModels.isEmpty()){
                                       storageCode = popuModels.get(0).getStorageCode();
                                   }

                                   isChecked();
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                stockMenu.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);
    }
    public void isChecked(){
        isChecked.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.isRelease(storageCode)
                .flatMap(new ResultDataParse<String>())
                .compose(new RxSchedulerTransformer<String>())
                .subscribe(new Consumer<String>() {
                               @Override
                               public void accept(String s) throws Exception {
                                   isChecked.setValue(LiveDataWrapper.success(s));

                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                isChecked.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);
    }


    public void lockStock(){
        lockStock.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.lockStock(new AddInventoryRequest(storageCode))
                .flatMap(new ResultDataParse<ResultEmpty>())
                .compose(new RxSchedulerTransformer<ResultEmpty>())
                .subscribe(new Consumer<ResultEmpty>() {
                               @Override
                               public void accept(ResultEmpty resultEmpty) throws Exception {
                                   lockStock.setValue(LiveDataWrapper.success(resultEmpty));
                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                lockStock.setValue(LiveDataWrapper.error(throwable,null));
                            }
                        });
        addDisposable(disposable);

    }


    public void addReport(){

    }

    public void jumpTo(InventoryResponse response){
        //根据不同的状态流转不同的页面
        if (TextUtils.equals("待确认",response.getStatusView())){
            ARouter.getInstance().build("/materialmanage/add/addreport")
                    .withBoolean("isSheetToReport",false)
                    .withString("sheetHeadCode",null)
                    .withString("reportHeadCode",response.getInventorynumber())
                    .navigation();
        } else  if (TextUtils.equals("待提交",response.getStatusView())){
            goToAddReport2(response,false,false,false);
        } else if (TextUtils.equals("等待审批",response.getStatusView())){
            goToAddReport2(response,false,false,true);
        } else if (TextUtils.equals("审批驳回",response.getStatusView())){
            goToAddReport2(response,true,false,true);
        } else if (TextUtils.equals("审批通过",response.getStatusView())){
            goToAddReport2(response,false,true,true);
//            Toast.makeText(getApplication(), response.getStatusView()+"：：：：：：跳转至添加盘点报告页面", Toast.LENGTH_SHORT).show();
        }

    }
    private void goToAddReport2(InventoryResponse response,boolean isCheckFailed,boolean isCheckSuccess, boolean isCanNotEdit){
        ARouter.getInstance().build("/materialmanage/inventoryReport/addreport2")
                .withBoolean("isCheckFailed",isCheckFailed)
                .withBoolean("isCheckSuccess",isCheckSuccess)
                .withBoolean("isCanNotEdit",isCanNotEdit)
                .withString("headCode",response.getInventorynumber())
                .navigation();
    }

    public void sort(PopuModel popuModel){
        meun.setValue(popuModel);
        if (TextUtils.equals("全部",popuModel.getName())){
            this.status = null;
        }
        this.status = popuModel.getDictDataId();
        getInventory(true);
    }



}
